package com.zbj.storm.old;

import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichSpout;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Random;

/**
 * TestWordSpout
 *
 * @author weigang
 * @create 2019-09-02
 **/
public class TestWordSpout extends BaseRichSpout {

    private SpoutOutputCollector collector;

    private Logger logger = LoggerFactory.getLogger(TestWordSpout.class);

    private Random random = new Random();

    @Override
    public void open(Map<String, Object> topoConf, TopologyContext context, SpoutOutputCollector collector) {
        this.collector = collector;
    }

    @Override
    public void nextTuple() {
        // Spouts 负责向拓扑中发送数据
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
        //每隔100ms就会从列表中随机选一个单词发出
        final String[] words = new String[]{"hellow", "lillcol", "study", "storm"};
        String word = words[random.nextInt(words.length)];
        logger.info("select word-> {}", word);
        collector.emit(new Values(word));
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        // 拓扑中的每个节点都必须声明它发出的元组的输出字段
        // 声明["word"]组件的输出字段
        declarer.declare(new Fields("word"));
    }
}